#include "time_sntp_driver.h"
#include "esp_log.h"
#include "fatfs_driver.h"
#include <sys/time.h>

static const char *TAG = "time_sntp_driver";

const char *file_time = MOUNT_POINT "/config/time";

void set_time(struct tm time_info)
{
    struct timeval tv;
    tv.tv_sec = mktime(&time_info);
    tv.tv_usec = 0;

    settimeofday(&tv, NULL);
    ESP_LOGI(TAG, "System time set successfully.");
}

void get_time_from_sys(char *time_str)
{
    time_t time_now;
    struct tm *time_info;
    time(&time_now);
    time_info = localtime(&time_now);
    strftime(time_str, 64, "%Y-%m-%d %H:%M:%S", time_info);
}

void get_time_file_name_format(char *time_str)
{
    time_t time_now;
    struct tm *time_info;
    time(&time_now);
    time_info = localtime(&time_now);
    strftime(time_str, 64, "%Y-%m-%d_%H-%M-%S", time_info);
}

void set_time_from_file()
{
    struct tm time_info = {
        .tm_sec = 30,
        .tm_min = 3,
        .tm_hour = 22,
        .tm_mday = 16,
        .tm_mon = 3-1,
        .tm_year = 2025 - 1900,
        .tm_wday = 6,
    };
    char time_str[64];
    FILE *f = fopen(file_time, "r"); // 以只读方式打开文件
    if (f == NULL)
    {
        fclose(f); // 关闭文件
        ESP_LOGW(TAG, "file_time:%s does not exist, create it", file_time);
        strftime(time_str, sizeof(time_str), "%Y %m %d %H %M %S", &time_info);
        ESP_ERROR_CHECK(fatfs_write_file(file_time, time_str));
    }
    else
    {
        int year, month, day, hour, min, sec;
        if (fscanf(f, "%d %d %d %d %d %d", &year, &month, &day, &hour, &min, &sec) == 6)
        {
            ESP_LOGI(TAG, "Time loaded from SD card: %d %d %d %d %d %d", year, month, day, hour, min, sec);
            time_info.tm_year = year - 1900;
            time_info.tm_mon = month - 1;
            time_info.tm_mday = day;
            time_info.tm_hour = hour;
            time_info.tm_min = min;
            time_info.tm_sec = sec;
        }
        fclose(f); // 关闭文件
    }
    set_time(time_info);
}

void save_time_into_file()
{
    time_t time_now;
    struct tm *time_info;
    char time_str[64];
    time(&time_now);
    time_info = localtime(&time_now);
    strftime(time_str, sizeof(time_str), "%Y %m %d %H %M %S", time_info);
    ESP_ERROR_CHECK(fatfs_write_file(file_time, time_str));
    ESP_LOGI(TAG, "save_time_into_file: %s", time_str);
}